package com.ruiyou.ub;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ActivityInfo;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;

/**
 * 辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
 **/
public class UWebChromeClient extends WebChromeClient {
    private final UWebView uwv;
    private Activity activity;
    private UWebView.StateListener mListener;
    private View savedView;

    public UWebChromeClient(UWebView uwv) {
        this.uwv = uwv;
        Context c = uwv.getContext();
        if (c instanceof Activity) {
            activity = (Activity) c;
            return;
        }
        while (c instanceof ContextWrapper) {
            if (c instanceof Activity) {
                activity = (Activity) c;
                return;
            }
            c = ((ContextWrapper) c).getBaseContext();
        }
    }

    /**
     * 显示进度
     *
     * @param view        WebView
     * @param newProgress 新的进度（0~100）
     */
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        if ((mListener = uwv.getStateListener()) != null) {
            mListener.onStateChanged(uwv,
                    mListener.STATE_PROGRESS, newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
        if ((mListener = uwv.getStateListener()) != null) {
            mListener.onStateChanged(uwv,
                    UWebView.StateListener.STATE_RECEIVED_TITLE, title);
        }
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        super.onShowCustomView(view, callback);
        showHideCustomView(view);
    }

    @Override
    public void onHideCustomView() {
        super.onHideCustomView();
        showHideCustomView(null);

    }

    private void showHideCustomView(View v) {
        int flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        Window win = activity.getWindow();
        if (v == null) {
            win.clearFlags(flags);
            activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            );
            activity.setContentView(savedView);
            return;
        }
        savedView = activity.findViewById(R.id.drawer_layout);
        activity.setContentView(new UVideoView(activity));
        FrameLayout parent = activity.findViewById(R.id.layout_video_container);
        parent.addView(v, 0);
        win.addFlags(flags);
        activity.setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        );
    }
}
